package com.example.java_chatroom.Controller;

import com.example.java_chatroom.model.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class TestWebSocketController extends TextWebSocketHandler {
//连接建立后
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在webSocket连接建立成功后，被自动调用
        System.out.println("TestController 连接成功");
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //webSocket收到消息后自动调用
        System.out.println("TestController 收到消息！" + message.toString());
        //在这里使用toString的方式可以显示收到的是什么消息
        // session是会话记录了通信双方是谁(session中持有了webSocket的通信连接) 可以直接将传过来的数据直接返回
        session.sendMessage(message);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //webSocket连接出现异常时候调用

        System.out.println("TestController 连接异常！");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //webSocket连接正常关闭后调用
        System.out.println("TestController 连接关闭");

    }
}
